var arr = []
let tool = {
	// 获取监听数据
	onBLEData(deviceId, callback) {
		// 十进制转十六进制
		const decimalToHexWithFraction = (decimal) => {
			decimal = decimal & 0xFF;
			// 将结果转换为十六进制字符串，并补齐到 2 位
			const hexStr = decimal.toString(16).padStart(2, '0').toUpperCase();
			return `0x${hexStr}`;
		}

		// 蓝牙数据转换操作
		const changeBleData = (value) => {
			try {
				// console.log('蓝牙硬件返回的原始数据', value)
				// 转换为不同数据视图
				const int8Array = new Int8Array(value);

				// 转换为普通数组
				const int8List = Array.from(int8Array);
				const result = [];
				for (let i = 0; i < int8List.length; i++) {
					if (int8List[i] == 85 && int8List[i + 1] == 97) {
						const subArray = int8List.slice(i, i + 20); // 假设每组数据长度为 20
						const data = {
							measured_acceleration_x: (((subArray[3] << 8) | (subArray[2] & 0xFF)) /
								32768 * 16 * 9.8),
							measured_acceleration_y: (((subArray[5] << 8) | (subArray[4] & 0xFF)) /
								32768 * 16 * 9.8),
							measured_acceleration_z: (((subArray[7] << 8) | (subArray[6] & 0xFF)) /
								32768 * 16 * 9.8),
							angular_velocity_x: (((subArray[9] << 8) | (subArray[8] & 0xFF)) / 32768 *
								2000),
							angular_velocity_y: (((subArray[11] << 8) | (subArray[10] & 0xFF)) / 32768 *
								2000),
							angular_velocity_z: (((subArray[13] << 8) | (subArray[12] & 0xFF)) / 32768 *
								2000),
						};
						result.push(data);
					}
				}
				return result;

				// let result = {}
				// console.log('int8List-', int8List)
				// if (int8List[1] == 97) {
				// 	result = {
				// 		measured_acceleration_x: (((decimalToHexWithFraction(int8List[3]) << 8) |
				// 			decimalToHexWithFraction(int8List[2])) / 32768 * 16 * 9.8),
				// 		measured_acceleration_y: (((decimalToHexWithFraction(int8List[5]) << 8) |
				// 			decimalToHexWithFraction(int8List[4])) / 32768 * 16 * 9.8),
				// 		measured_acceleration_z: (((decimalToHexWithFraction(int8List[7]) << 8) |
				// 			decimalToHexWithFraction(int8List[6])) / 32768 * 16 * 9.8),
				// 		angular_velocity_x: (((int8List[9] << 8) | int8List[8]) / 32768 * 2000),
				// 		angular_velocity_y: (((int8List[11] << 8) | int8List[10]) / 32768 * 2000),
				// 		angular_velocity_z: (((int8List[13] << 8) | int8List[12]) / 32768 * 2000),
				// 	};
				// }
				// return result;

			} catch (error) {
				console.error('数据转换出错:', error);
				uni.showToast({
					title: '数据转换出错，请检查蓝牙数据',
					icon: 'none'
				});
				return null;
			}
		};

		const enableNotify = (deviceId, serviceId, characteristicId) => {
			uni.notifyBLECharacteristicValueChange({
				state: true,
				deviceId: deviceId,
				serviceId: serviceId,
				characteristicId: characteristicId,
				success: (res) => {
					console.log('启用 notify 功能成功', res);
					// 监听特征值变化
					uni.onBLECharacteristicValueChange((res) => {
						// console.log('监听到的数据res', res)
						const data = changeBleData(res.value);
						// 触发自定义事件，将处理后的数据传出去
						callback(data);
						// 如果数据为空，可选择不调用回调或者传递一个默认空对象
						// callback({}); 
						// arr.push(res.value)
					});
				},
				fail: (err) => {
					console.error('启用 notify 功能失败', err);
					uni.showToast({
						title: `启用 notify 功能失败: ${err.errMsg}`,
						icon: 'none'
					});
				}
			});
		};
		const writeDataToCharacteristic = (deviceId, serviceId, characteristicId, data) => {
			return new Promise((resolve, reject) => {
				uni.writeBLECharacteristicValue({
					deviceId: deviceId,
					serviceId: serviceId,
					characteristicId: characteristicId,
					value: data,
					success: (res) => {
						console.log('数据发送成功', res);
						resolve(res);
					},
					fail: (err) => {
						console.error('数据发送失败', err);
						uni.showToast({
							title: `数据发送失败: ${err.errMsg}`,
							icon: 'none'
						});
						reject(err);
					}
				});
			});
		};
		const sendMultipleCommands = async (deviceId, serviceId, characteristicId, commands) => {
			for (const command of commands) {
				const dataArray = command.split(' ').map(item => parseInt(item, 16));
				const dataBuffer = new Uint8Array(dataArray).buffer;
				try {
					await writeDataToCharacteristic(deviceId, serviceId, characteristicId, dataBuffer);
				} catch (error) {
					console.error('发送指令时出错:', error);
					break;
				}
			}
		};
		const getCharacteristics = (deviceId, serviceId) => {
			uni.getBLEDeviceCharacteristics({
				deviceId: deviceId,
				serviceId: serviceId,
				success: (res) => {
					console.log('获取设备特征成功', res);
					const characteristics = res.characteristics;
					characteristics.forEach((characteristic) => {
						if (characteristic.properties.write) {
							// 定义多段指令
							const commands = [
								'FF AA 69 88 B5',
								'FF AA 03 0B 00',
								'FF AA 00 00 00',
								'FF AA 69 88 B5',
								'FF AA 1F 00 00',
								'FF AA 00 00 00'
							];
							sendMultipleCommands(deviceId, serviceId,
								characteristic.uuid,
								commands);
						}
						if (characteristic.properties.notify) {
							// 启用 notify 功能
							setTimeout(() => {
								enableNotify(deviceId, serviceId, characteristic
									.uuid);
							}, 500)
						}
					});
				},
				fail: (err) => {
					console.error('获取设备特征失败', err);
					uni.showToast({
						title: `获取设备特征失败: ${err.errMsg}`,
						icon: 'none'
					});
				}
			});
		};

		const getServices = (deviceId) => {
			uni.getBLEDeviceServices({
				deviceId: deviceId,
				success: (res) => {
					const services = res.services;
					console.log('该服务下的所有特征', res)
					services.forEach((service) => {
						// 获取该服务下的所有特征
						getCharacteristics(deviceId, service.uuid);
					});
				},
				fail: (err) => {
					console.error('获取设备服务失败', err);
					uni.showToast({
						title: `获取设备服务失败: ${err.errMsg}`,
						icon: 'none'
					});
				}
			});
		};

		getServices(deviceId);
	},
	// 关闭蓝牙连接
	closeBLEContent(deviceId) {
		// 关闭蓝牙连接
		uni.closeBLEConnection({
			deviceId,
			success: (res) => {
				console.log('关闭蓝牙连接成功', res);
				uni.setStorageSync('deviceData', {
					localName: '手机'
				});
			},
			fail: (err) => {
				console.error('关闭蓝牙连接失败', err);
				uni.showToast({
					title: `关闭蓝牙连接失败: ${err.errMsg}`,
					icon: 'none'
				});
			}
		});
	},
	// 关闭蓝牙模块
	closeBLEModal() {
		uni.closeBluetoothAdapter({
			success: (res) => {
				console.log('关闭蓝牙模块成功', res);
				uni.setStorageSync('deviceData', {
					localName: '手机'
				});
			},
			fail: (err) => {
				console.error('关闭蓝牙模块失败', err);
				uni.showToast({
					title: `关闭蓝牙模块失败: ${err.errMsg}`,
					icon: 'none'
				});
			}
		});
	},
	// 关闭监听数据操作
	closeOnBLE() {
		// 关闭 notify 监听
		console.log('已关闭数据监听');
		console.log('监听到的数据', arr)
		uni.offBLECharacteristicValueChange();
	},
	// 关闭蓝牙连接状态监听
	closeOnBleStatus() {
		uni.offBLEConnectionStateChange()
	},
	// 初始化蓝牙连接状态监听
	initBluetoothConnectionListener(callback) {
		// 更新设备缓存
		const updateDeviceCache = (deviceId, connected, callback) => {
			let deviceData = {};
			if (!connected) {
				// 	// 设备已连接，将设备 ID 存入缓存
				// 	deviceData.deviceId = deviceId;
				// 	deviceData.localName = 'WT901BLE67';
				// } else {
				// 设备已断开连接，将缓存设置为 '手机'
				deviceData.localName = '手机';
				uni.setStorageSync('deviceData', deviceData);
			}
			if (typeof callback == 'function') {
				callback(deviceData);
			}
		};
		// 监听蓝牙设备连接状态变化
		uni.onBLEConnectionStateChange((res) => {
			const {
				deviceId,
				connected
			} = res;
			updateDeviceCache(deviceId, connected, callback);
		});
	},
	// 获取当前蓝牙连接状态
	getBlueStatus() {
		uni.getConnectedBluetoothDevices({
			services: uni.getStorageSync('deviceData')
				?.advertisServiceUUIDs, // 传入空数组表示获取所有已连接的设备
			success: (res) => {
				console.log('蓝牙连接状态', res)
				if (res.devices.length == 0 || !res.devices.some(item => item.name == 'WT901BLE67')) {
					let deviceData = {}
					deviceData.localName = '手机';
					uni.setStorageSync('deviceData', deviceData);
				}
			},
			fail: (err) => {
				console.error('蓝牙连接状态错误', err);
				let deviceData = {}
				deviceData.localName = '手机';
				uni.setStorageSync('deviceData', deviceData);
			}
		});
	},
	leastSquaresRegression(xArray, yArray) {
		if (xArray.length != yArray.length || xArray.length == 0) {
			throw new Error("两个数组必须长度相同且至少包含一个点");
		}
		const xVals = xArray.map((x, idx) => {
			const value = Number(x);
			return value;
		});
		const yVals = yArray.map((y, idx) => {
			const value = Number(y);
			return value;
		});
		const n = xVals.length;
		let sumX = 0,
			sumY = 0,
			sumXY = 0,
			sumX2 = 0;

		for (let i = 0; i < n; i++) {
			sumX += xVals[i];
			sumY += yVals[i];
			sumXY += xVals[i] * yVals[i];
			sumX2 += xVals[i] * xVals[i];
		}

		const denominator = n * sumX2 - sumX * sumX;
		if (denominator == 0) {
			throw new Error("无法计算斜率，数据可能有问题");
		}

		const slope = (n * sumXY - sumX * sumY) / denominator;
		const intercept = (sumY - slope * sumX) / n;

		return {
			slope,
			intercept
		};
	}
};

export default tool;